package com.syuchen.client.http;

import com.alibaba.fastjson.JSON;
import com.syuchen.client.Client;
import com.syuchen.common.Invocation;
import com.syuchen.common.URL;
import com.syuchen.protocol.http.HttpRequestEncoder;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class HttpClient implements Client {

    @Override
    public Object send(URL url, Invocation invocation) throws Exception {
        String apiUrl = invocation.getInterfaceName() + "/" + invocation.getMethodName();
        String content = JSON.toJSONString(invocation);
        String httpMsg = HttpRequestEncoder.encode(apiUrl, url.getHostname(), content);
        Socket connectionSocket = ConnectionPool.getConnectionSocket(url.getHostname(), url.getPort());
        BufferedWriter requestWriter = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream(), StandardCharsets.UTF_8));
        requestWriter.write(httpMsg);
        requestWriter.flush();
        return HttpDecoder.decode(connectionSocket.getInputStream());
    }
}
